package com.nms.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.apache.http.protocol.HTTP;
import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nms.model.News;
import com.nms.model.Role;
import com.nms.model.User;
import com.nms.model.pojo.PageParam;
import com.nms.service.CKEditorService;
import com.nms.service.NewsService;
import com.nms.service.UserService;
import com.nms.util.SystemUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 移动客户端请求处理action
 * 
 * @author Administrator
 *
 */
public class WapAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private NewsService newsService;
	private UserService userService;
	private CKEditorService ckEditorService;
	
	public void loadNews(){
			/* 获得HttpServletRequest对象 */
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String id = request.getParameter("id");
		/* 根据请求参数生成一个新闻的访问路径 */
		String url = SystemUtil.getInstance().getAppDir(request)
				+ SystemUtil.contentBasePath + id + ".news";
		try{
			News news = newsService.findById(id);
			news.setContent(ckEditorService.get(url));
			String json = JSON.toJSONString(news);
			response.setHeader("Content-Type","application/json");
			response.setCharacterEncoding(HTTP.UTF_8);
			PrintWriter out = response.getWriter();
			out.println(json);
			response.setStatus(HttpStatus.SC_OK);
			out.close();
		} catch(Exception e){
			e.printStackTrace();
			response.setStatus(HttpStatus.SC_FAILED_DEPENDENCY);
		}
	}
	
	public void listNews(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String i = request.getParameter("i");
		String s = request.getParameter("s");
		int index = 0, size = 10;
		if(i != null && i != ""){
			index = Integer.parseInt(i);
		}
		if(s != null && s != ""){
			size = Integer.parseInt(s);
		}
		PageParam p = new PageParam(index, size, 0, "");
		List<News> news = newsService.findByPage(p);
		JSONArray a = new JSONArray();
		for (News n : news) {
			JSONObject o = new JSONObject();
			o.put("id", n.getId());
			o.put("mainTitle", n.getMainTitle());
			o.put("topLine", n.getTopLine());
			o.put("releaseTime", n.getReleaseTime());
			a.add(o);
		}
		String json = JSON.toJSONString(a);
		System.out.println(json);
		response.setHeader("Content-Type","application/json");
		response.setCharacterEncoding(HTTP.UTF_8);
		try {
			PrintWriter out = response.getWriter();
			out.println(json);
			response.setStatus(HttpStatus.SC_OK);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			response.setStatus(HttpStatus.SC_FAILED_DEPENDENCY);
		}
	}
	public String commentNews(){
		return null;
	}
	public String manageNews(){
		return null;
	}
	
	/**
	 * 用户注册
	 */
	public void register(){
		User user = new User();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();

		try {
			BufferedReader reader = request.getReader();
			String buffer = null,content = "";
			while((buffer = reader.readLine()) != null){
				content += buffer;
			}
			System.out.println("username = " + content);
			JSONObject o = JSONObject.parseObject(content);
			
			user.setUsername(o.getString("username"));
			user.setPassword(o.getString("password"));
			user.setNickname(o.getString("nickname"));

			Role role = new Role(5, "普通用户", "系统的一般用户");
			user.setRole(role);
			user.setGrade(0);
			user.setProperty(0);
			user.setHomepage("http://www.baidu.com");
			user.setRegisterTime(new Date());
			user.setState(1);
			if(user.getNickname() == null || user.getNickname().equals("")){
				user.setNickname(user.getUsername());
			}
			if ((userService.register(user)) == 1) {
				String json = JSONObject.toJSONString(user);
				response.setHeader("Content-Type","application/json");
				response.setCharacterEncoding(HTTP.UTF_8);
				PrintWriter out = response.getWriter();
				out.println(json);
				response.setStatus(HttpStatus.SC_OK);
				out.close();
			} else {
				response.setStatus(HttpStatus.SC_FAILED_DEPENDENCY);
			}
		} catch (IOException e1) {
			response.setStatus(HttpStatus.SC_FAILED_DEPENDENCY);
			e1.printStackTrace();
		}
	}
	
	/**
	 * 移动客户端登录
	 */
	public void login(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();

		User user = new User();
		if(!request.getMethod().equals("POST")){
			/** 禁止使用非POST方式提交登录信息 */
			response.setStatus(HttpStatus.SC_FORBIDDEN);
			return;
		}
		try {
			BufferedReader reader = request.getReader();
			String buffer = null,content = "";
			while((buffer = reader.readLine()) != null){
				content += buffer;
			}
			System.out.println("content = " + content);
			System.out.println(request.getContentType());
			JSONObject o = JSONObject.parseObject(content);
			
			user.setUsername(o.getString("username"));
			user.setPassword(o.getString("password"));
			
			if ((user = userService.login(user)) != null) {
				Map<String, Object> session = ActionContext.getContext()
						.getSession();
				session.put("user", user);
				session.put("loginTime", new Date());
				
				String json = JSONObject.toJSONString(user);
				response.setHeader("Content-Type","application/json");
				response.setCharacterEncoding(HTTP.UTF_8);
				PrintWriter out = response.getWriter();
				out.println(json);
				response.setStatus(HttpStatus.SC_OK);
				out.close();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
	/**
	 * 登出
	 */
	public void logout(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("user") != null) {
			session.put("user", null);
			session.put("loginTime", null);
			session.remove("user");
			session.remove("loginTime");
		}
	}
	
	@Override
	public String execute() {
		return "success";
	}
	////////////////////////////////////////
	
	public NewsService getNewsService() {
		return newsService;
	}
	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public CKEditorService getCkEditorService() {
		return ckEditorService;
	}

	public void setCkEditorService(CKEditorService ckEditorService) {
		this.ckEditorService = ckEditorService;
	}
}
